package com.three.zklock;

import com.three.api.spi.common.CacheManagerFactory;
import com.three.zk.lock.DistributedLock;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by mathua on 2017/6/29.
 */
public class ZkLockTest {

    @Before
    public void init() {
        CacheManagerFactory.create().init();
    }

    @Test
    public void testLock() {
        DistributedLock.getZK();
        Runnable task1 = new Runnable(){
            public void run() {
                DistributedLock lock = null;
                try {
                    lock = new DistributedLock("002");
                    lock.lock();
                    System.out.println("进入锁成功");
//                    Thread.sleep(20000);
                    System.out.println("===Thread " + Thread.currentThread().getId() + " running");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if(lock != null)
                        lock.unlock();
                }

            }

        };
        new Thread(task1).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        ConcurrentTest.ConcurrentTask[] tasks = new ConcurrentTest.ConcurrentTask[5];
        for(int i=0;i<tasks.length;i++){
            ConcurrentTest.ConcurrentTask task3 = new ConcurrentTest.ConcurrentTask(){
                public void run() {
                    DistributedLock lock = null;
                    try {
                        lock = new DistributedLock("kkkx");
                        lock.lock();
                        System.out.println("Thread " + Thread.currentThread().getId() + " running");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        lock.unlock();
                    }

                }
            };
            tasks[i] = task3;
        }
        new ConcurrentTest(tasks);//执行task
    }

}
